package com.fly.core.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ShellExecutor
{
    /**
     * 返回脚本执行结果
     * 
     * @param command
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static List<String> exec(String command)
    {
        try
        {
            String[] cmd = SystemUtils.IS_OS_WINDOWS ? new String[] {"cmd", "/c", command} : new String[] {"sh", "-c", command};
            ProcessBuilder processBuilder = new ProcessBuilder(cmd);
            processBuilder.redirectErrorStream(false);
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            log.info("###### 命令输出 ######");
            String line;
            List<String> results = new ArrayList<>();
            while ((line = reader.readLine()) != null)
            {
                log.info(line);
                results.add(line);
            }
            log.info("###### 命令执行完成，退出码: {} ######", process.waitFor());
            return results;
        }
        catch (IOException | InterruptedException e)
        {
            log.error(e.getMessage(), e);
            return Collections.emptyList();
        }
    }
    
    /**
     * execute命令
     * 
     * @param command
     * @return 执行结果
     * @throws IOException
     */
    public static String execute(String command)
    {
        return StringUtils.join(exec(command), System.lineSeparator());
    }
}
